import 'package:reabampos/src/reabam/operation/bean/check_app_update/Request_check_app_update.dart';
import 'package:reabampos/src/reabam/operation/bean/login/request_login.dart';
import 'package:reabampos/src/reabam/operation/bean/login/request_user_info.dart';
import 'package:reabampos/src/reabam/operation/rb_api.dart';
import 'package:reabampos/src/reabam/operation/rb_config.dart';
import 'package:reabampos/src/reabam/operation/rb_enum.dart';
import 'package:reabampos/src/reabam/ui/update_app/pagestate_update_app.dart';
import 'package:xsdk_flutter/xsdk/framework/base/xsdk_function.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';

//登录
abstract class RBLoginUtils {


  /*
  登录
   原生+flutter框架: 通知原生登录失败,返回原生界面
   RBBaseApi.notifyFlutterLoginFailAndBackToNative();
   */
  static void login(
      XPageState pageState,
      {
        required String loginName,
        required String loginPWD,
        String? groupId,
        required XFunctionResultCallback onCallback,
      }
      ){

    //
    XSharePreferencesUtils.saveString(RBConfigs.SP_groupId, "");
    XSharePreferencesUtils.saveString(RBConfigs.SP_companyId, "");
    XSharePreferencesUtils.saveString(RBConfigs.SP_userId, "");

    String loginType='checkstand';

    pageState.showLoading(isOurSideCanClick:false);
    RBBaseApi.login(
      mobile: loginName,
      loginWord: XJiamiUtils.strToMd5(loginPWD),
      appVersion: '${RBConfigs.versionName}',
      clientVersion: '${RBConfigs.versionName}',
      appType: 'phone_android',
      loginType: loginType,
      groupId: groupId,
      jpushRegId: '',
      succeed: (responseqqq, Map<String, dynamic> responseMap, Map<String, dynamic> headers_response) {

        //如果服务端没有返回serverAddress,给一个无效的url,避免后面activity请求崩溃
        String? serverAddress = responseMap['data']?['serverAddress'];
        String? zuulServerAddress = responseMap['data']?['zuulServerAddress'];

        if (XStringUtils.isEmpty(serverAddress) || !serverAddress!.startsWith("http")) {
          serverAddress = "http://127.0.0.1";
        }

        if (XStringUtils.isEmpty(zuulServerAddress) || !zuulServerAddress!.startsWith("http")) {
          zuulServerAddress = "http://127.0.0.1";
        }
        XSharePreferencesUtils.saveString(RBConfigs.SP_serverAddress,serverAddress);
        XSharePreferencesUtils.saveString(RBConfigs.SP_zuulServerAddress,zuulServerAddress);

        //切换品牌需要重新登录,因此记录用户和密码
        XSharePreferencesUtils.saveString(RBConfigs.SP_loginName,loginName);
        XSharePreferencesUtils.saveString(RBConfigs.SP_loginPwd,loginPWD);

        //
        XSharePreferencesUtils.saveString(RBConfigs.SP_tokenId, responseMap['data']?['tokenId']??'');
        XSharePreferencesUtils.saveString(RBConfigs.SP_MENUS,XJsonUtils.obj2Json(responseMap['data']?['menus']??[]));
        XSharePreferencesUtils.saveString(RBConfigs.SP_FUNS,XJsonUtils.obj2Json(responseMap['data']?['funs']??[]));
        XSharePreferencesUtils.saveString(RBConfigs.SP_FUNCONFIGS,XJsonUtils.obj2Json(responseMap['data']?['funConfigs']??[]));
        XSharePreferencesUtils.saveString(RBConfigs.SP_CompanyName,responseMap['data']?['companyName']??'');
        XSharePreferencesUtils.saveString(RBConfigs.SP_CompanyCode,responseMap['data']?['companyCode']??'');
        XSharePreferencesUtils.saveString(RBConfigs.SP_GroupName,responseMap['data']?['groupName']??'');
        XSharePreferencesUtils.saveString(RBConfigs.SP_BrandLogo,responseMap['data']?['brandLogo']??'');

        XSharePreferencesUtils.saveString(RBConfigs.SP_groupId, responseMap['data']?['groupId']??'');
        XSharePreferencesUtils.saveString(RBConfigs.SP_companyId, responseMap['data']?['companyId']??'');
        XSharePreferencesUtils.saveString(RBConfigs.SP_userId, responseMap['data']?['fid']??'');
        XSharePreferencesUtils.saveString(RBConfigs.SP_UserName, responseMap['data']?['userName']??'');
        XSharePreferencesUtils.saveString(RBConfigs.SP_UserCode, responseMap['data']?['userCode']??'');
        XSharePreferencesUtils.saveString(RBConfigs.SP_UserTypeName, responseMap['data']?['userTypeName']??'');

        XSharePreferencesUtils.saveString(RBConfigs.SP_ClientName, responseMap['data']?['sysName']??'');

        //是否默认当前登录账户为导购
        XSharePreferencesUtils.saveString(RBConfigs.SP_guideSet, XJsonUtils.obj2Json(responseMap['data']?['guideSet']??Bean_login_guide()));
        //商户保证金
        int merchantDeposit = responseMap['data']?['merchantDeposit']??0;
        XSharePreferencesUtils.saveBool(RBConfigs.SP_Shanghu_baozhengjin, merchantDeposit == 1);

        //用户信息详情
        _getUserAuthStatus(pageState,onCallback:onCallback);

      },
      failed: (String code, String msg) {
        pageState.hideLoading();
        pageState.toast(msg);
      },
    );

  }


  //用户更多信息
  static void _getUserAuthStatus(
      XPageState pageState,{
        required XFunctionResultCallback onCallback,
      }
      ) {
    RBBaseApi.getUserAuthStatus(succeed: (LoginInfoResponse response,
        Map<String, dynamic> responseMap, Map<String, dynamic> headers_response) {
      if (response.retailConfig != null) {
        //是否锁定库存
        XSharePreferencesUtils.saveString(
            RBConfigs.STOCKLOCK, '${response.retailConfig!.retailStockLockEnable}');
        XSharePreferencesUtils.saveString(
            RBConfigs.REFUND_REASONS_ENABLE, '${response.retailConfig!.refundReasonsEnable}');
        XSharePreferencesUtils.saveString(
            RBConfigs.CANCEL_REASONS_ENABLE, '${response.retailConfig!.cancelReasonsEnable}');
        XSharePreferencesUtils.saveString(
            RBConfigs.NOT_PAY_PEND_ORDER, '${response.retailConfig!.notPayPendOrder}');
        XSharePreferencesUtils.saveString(
            RBConfigs.NOT_PAY_ORDER, '${response.retailConfig!.notPayOrder}');
        XSharePreferencesUtils.saveString(
            RBConfigs.PART_PAY_PEND_ORDER, '${response.retailConfig!.partPayPendOrder}');
        XSharePreferencesUtils.saveString(
            RBConfigs.NOT_MEAL_ORDER, '${response.retailConfig!.notMealOrder}');

        Bean_configRetailOrder? configRetailOrder = response.retailConfig?.configRetailOrder;
        if (configRetailOrder != null) {
          XSharePreferencesUtils.saveBool(
              RBConfigs.Order_PostingDate_Modifiable, configRetailOrder.orderPostingDateModifiable);
          XSharePreferencesUtils.saveBool(RBConfigs.Refund_PostingDate_Modifiable,
              configRetailOrder.refundPostingDateModifiable);
        }
      }

      String headImageUrl = response.headImageUrl ?? '';
      XSharePreferencesUtils.saveString(RBConfigs.SP_UserLogo, headImageUrl);
      XSharePreferencesUtils.saveString(RBConfigs.SP_UserSex, response.sex??'男');

      //登录完成,通知外界
      pageState.hideLoading();
      onCallback('ok');

    }, failed: (String code, String msg) {
      pageState.hideLoading();
      pageState.toast(msg);
    });
  }




  //检查版本升级
  static void checkAppUpdate(XPageState pagestate){

    if(XFlutterUtils.isAndroid() && RBConfigs.versionType==VersionType.baodaoVersion){

      RBBaseApi.checkAppVersionUpdate(
        appCode: '自助收银',
        succeed: (ResponseCheckAppUpdate response, Map<String, dynamic> responseMap, Map<String, dynamic> headers_response) {

          BeanUpdateAppVersionData? data=response.data;
          if (data!=null){
            BeanUpdateAppVersionInfo? info=data.info;
            if (info!=null){
              try{
                //最新版本
                int sversion=int.tryParse('${info.version}')??0;
                XLogUtils.printLog('---服务端最新版本=$sversion');
                //当前版本
                int cversion=RBConfigs.version;
                if (sversion>cversion){
                  //
                  pagestate.startPage(UpdateAPPStatePage(info));
                }

              }catch (e){
                XLogUtils.printLog('---checkAppVersionUpdate报错: $e');
              }

            }
          }

        },
        failed: (String code,String msg){

        },
      );
    }
  }




}
